<?php
/**
 * Created by lzl
 * Date: 2021 2021/11/19
 * Time: 14:30
 */
namespace App\Services\Api;
use App\Exceptions\RequestException;
use App\Forms\ConfigForms;
use App\Forms\UserForms;
use App\Forms\WithdrawForms;
use App\Models\User;
use App\Models\UserBalanceLog;
use App\Models\Withdraw;
use App\Services\BaseServices as Base;
use EasyWeChat\Factory;


class WithdrawServices extends Base
{


    /**
     * @param $validated
     * @return Withdraw|\Illuminate\Database\Eloquent\Model
     * @throws RequestException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Throwable
     */
    public function send($validated)
    {
        $user = (new UserForms())->getUserDetail(UID);

        $this->validatedSend($user, $validated);

        \DB::beginTransaction();

        try{
            $validated['uid'] = UID;
            $validated['order_sn'] = get_order_no('WTD');
            $model = (new WithdrawForms())->createWithdraw($validated);

            $app = Factory::payment(config("wechat.payment.default"));

            $param = [
                'partner_trade_no' => $model->order_sn,
                'openid'           => $user->openid,
                'check_name'       => 'NO_CHECK', // NO_CHECK：不校验真实姓名
//            're_user_name'     => "nickname", // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                'amount'           => $validated['amount'] * 100,
                'desc'             => "分润提现"
            ];

            \Log::channel('wechat')->info('申请微信代付：', $param);

            $result = $app->transfer->toBalance($param);

            \Log::channel('wechat')->info('代付同步返回：', $result);

            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

                $model->update([
                    'status'       => Withdraw::SUCCESS,
                    'success_time' => date('Y-m-d H:i:s'),
                ]);

                (new UserForms())->balanceLogCreate([
                    'uid' => UID,
                    'type' => UserBalanceLog::OUT,
                    'amount' => $validated['amount'],
                    'msg' => '分润提现',
                ]);

                //扣除用户余额
                (new UserForms())->editMsg(UID,[
                   'balance' => bcsub($user->balance, $validated['amount'],2),
                    'withdraw_amount' => bcadd($user->withdraw_amount, $validated['amount'],2)
                ]);

                \DB::commit();

                return $model;
            }

            throw new RequestException($result['err_code_des'] ?? $result['return_msg']);

        }catch (\Exception $e){

            \DB::rollBack();
            throw new RequestException($e->getMessage());
        }


    }


    /**
     * @param User $user
     * @param $validated
     * @throws RequestException
     */
    public function validatedSend(User $user, $validated)
    {
        $configForms = new ConfigForms();

        $min = $configForms->getDetail('withdraw_min')->value;

        $max = $configForms->getDetail('withdraw_max')->value;

        if($validated['amount'] < $min){
            throw new RequestException('最低提现金额为 '.$min.' 元');
        }

        if($validated['amount'] > $max){
            throw new RequestException('单次最高提现金额为 '.$max.' 元');
        }

        if($validated['amount'] > $user->balance){
            throw new RequestException('余额不足');
        }
    }
}